﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;

namespace SCM.Model
{
    /// <summary>
    /// Token
    /// </summary>
    public class AccessToken
    {
        /// <summary>
        /// 手机号
        /// </summary>
        public string Phone { get; set; }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="access"></param>
        /// <returns></returns>
        public static string Encry(AccessToken access)
        {
            if (access == null)
                return "";
            string json = JsonConvert.SerializeObject(access);
            byte[] key = new byte[8];
            Random random = new Random();
            for (int i = 0; i < 8; i++)
            {
                key[i] = (byte)random.Next(255);
            }
            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8);
            bw.Write(key);
            byte[] buffer = Encoding.Default.GetBytes(json);
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = (byte)(buffer[i] ^ key[i % key.Length]);
            }
            bw.Write(buffer);
            return Convert.ToBase64String(((MemoryStream)bw.BaseStream).ToArray());
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static AccessToken Decry(string accessToken)
        {
            if (accessToken.Length < 8)
            {
                return null;
            }
            MemoryStream ms = new MemoryStream();
            byte[] buffer = Convert.FromBase64String(accessToken);
            ms.Write(buffer, 0, buffer.Length);
            ms.Position = 0;
            BinaryReader br = new BinaryReader(ms, Encoding.UTF8);
            byte[] key = br.ReadBytes(8);
            buffer = ((MemoryStream)br.BaseStream).ToArray();
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = (byte)(buffer[i] ^ key[i % key.Length]);
            }
            return JsonConvert.DeserializeObject<AccessToken>(Encoding.Default.GetString(buffer));
        }
    }
}
